package com.chandon.juc.thread_basic;

import java.util.concurrent.*;

/**
 * 线程创建的方式
 *
 * @author Dong
 * @version 1.0
 * @date 2021-04-03 13:15
 */

public class T01_HowToCreateThread {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        /**
         * 1.继承Thread类，重写run方法，start启动,没有返回值
         */
//        new extendsThreadClass().start();


        /**
         * 2.实现Runnable，重写run方法,Thread包装后start，没有返回值
         */
//        new Thread( new implementsRunnable()).start();
//        Lambda写法
//        new Thread(()-> System.out.println("implemets Runnable方式创建线程")).start();

//         Runnable结合TheadPool

       /* ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(new implementsRunnable());
        executorService.shutdown(); */


        /**
         * 3.有返回值的线程，实现Callable
         */
        // 结合线程池使用
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<String> future = executorService.submit(new ImplementsCallable());
        System.out.println(future.get());
        executorService.shutdown();


        // Callable单独使用
        FutureTask<String> futureTask = new FutureTask<String>(new ImplementsCallable());
        new Thread(futureTask).start();
        String s = futureTask.get();
        System.out.println(s);

    }

    static class extendsThreadClass extends Thread {
        @Override
        public void run() {
            System.out.println("1.继承Thread类，重写run方法，start启动,没有返回值");
        }
    }

    static class ImplementsRunnable implements Runnable {

        @Override
        public void run() {
            System.out.println("2.实现Runnable，重写run方法,Thead包装后start，没有返回值");
        }
    }

    static class ImplementsCallable implements Callable<String> {
        @Override
        public String call() throws Exception {
            System.out.println("Callable方式创建线程");
            return "3.实现Callable,FutureTask包装,Thread方式启动";
        }
    }

}
